﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using Microsoft.SharePoint;
using System.Web.Script.Serialization;
using System.IO;

namespace Adartse.Sharepoint
{
    public static class Utilities
    {
        public static string WebRoot
        {
            get
            {
                if (SPContext.Current.Site.ServerRelativeUrl.Length != 1)
                {
                    var i = SPContext.Current.Site.RootWeb.Url.LastIndexOf(SPContext.Current.Site.ServerRelativeUrl);
                    return SPContext.Current.Site.RootWeb.Url.Substring(0, i);
                }
                else
                    return SPContext.Current.Site.RootWeb.Url;
            }

        }

        public static string JSONSerializer<T>(T t)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            return js.Serialize(t);
        }

        public static T JSONDeserializer<T>(string data)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            return js.Deserialize<T>(data);
        }

        public static string RenderControl(Control ctrl)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter tw = new StringWriter(sb);
            HtmlTextWriter hw = new HtmlTextWriter(tw);

            ctrl.RenderControl(hw);
            return sb.ToString();
        }

        public static string UnformatText(string html)
        {
            return System.Text.RegularExpressions.Regex.Replace(html, "<[^>]*>", "").Replace(Environment.NewLine, "");
        }

    }
}
